package com.ziyia.cameraalbumtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final int TAKE_PHOTO = 1;
    private static final int FROMAIBUM = 2;
    private Uri imageUri;
    private File outputImage;
    private Button takePhotoBtn, fromAlbumBtn;
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
// 创建File对象，用于存储拍照后的图片
                outputImage = new File(getExternalCacheDir(), "tempImage.jpg");
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                try {
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this, "com.ziyia.cameraalbumtest.FileProvider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
            }
        });

        fromAlbumBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                // 指定只显示图片
                intent.setType("image/*");
                startActivityForResult(intent, FROMAIBUM);
            }
        });
    }

    private void init() {

       takePhotoBtn = findViewById(R.id.takePhotoBin);
       fromAlbumBtn = findViewById(R.id.fromAlbumBtn);
       imageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        imageView.setImageBitmap(rotateIfRequired(bitmap)); // 将裁剪后的照片显示出来
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case FROMAIBUM:

                if (resultCode == Activity.RESULT_OK && data != null) {
                    Uri uri = data.getData();
                    try {


                        Bitmap bp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                        imageView.setImageBitmap(bp);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    private Bitmap rotateIfRequired(Bitmap bitmap) {
        Bitmap bp = null;
        try {
            ExifInterface exifInterface = new ExifInterface(outputImage.getPath());
            int attributeInt = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (attributeInt) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    bp = rotateBitmap(bitmap, 90);
                break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    bp = rotateBitmap(bitmap, 100);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    bp = rotateBitmap(bitmap, 270);
                    break;
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return bp == null ? bitmap : bp;
    }

    private Bitmap rotateBitmap(Bitmap bitmap, Integer i) {
        Matrix matrix = new Matrix();
        matrix.postRotate(Float.valueOf(i));
        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return bitmap1;
    }


}